import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/auth.config';
import { prisma } from '@/lib/prisma';
import { NextResponse } from 'next/server';
import { revalidatePath } from 'next/cache';

export async function POST(request: Request) {
  try {
    const session = await getServerSession(authOptions);
    
    // 添加详细的日志
    console.log('Creating trip with session:', session);
    
    if (!session?.user?.id) {
      console.error('No user ID in session:', session);
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const body = await request.json();
    console.log('Request body:', body);

    // 创建行程
    const trip = await prisma.trip.create({
      data: {
        title: body.title,
        description: body.description,
        startDate: new Date(body.startDate),
        endDate: new Date(body.endDate),
        isPublic: body.isPublic,
        userId: session.user.id,  // 直接使用 session 中的用户 ID
        activities: {
          create: body.activities?.map((activity: any) => ({
            title: activity.title,
            description: activity.description,
            date: new Date(activity.date),
          }))
        }
      },
      include: {
        activities: true,
      }
    });

    console.log('Created trip:', trip);

    // 重新验证多个相关路径
    revalidatePath('/trips');
    revalidatePath('/profile');
    revalidatePath('/popular-trips');
    
    return NextResponse.json(trip);
  } catch (error: any) {
    console.error('Create trip error:', {
      error,
      message: error.message,
      code: error.code,
      meta: error.meta,
    });
    
    return NextResponse.json(
      { error: '创建行程失败', details: error.message },
      { status: 500 }
    );
  }
} 